<template>
  <div class="container flex flex_column">
    <!-- 搜索     -->
    <div class="btnCon flex flex_between" style="border-bottom: none">
      <div class="plop">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="addClick"
          >新建</el-button
        >
      </div>
      <!--      搜索框-->
      <div class="search">
        <el-input
          v-model="search.likeWords"
          placeholder="输入关键字"
          size="small"
          @keyup.enter.native="getAllLists"
        >
          <el-button
            slot="append"
            v-loading="searchLoading"
            type="primary"
            icon="el-icon-search"
            :disabled="searchLoading"
            element-loading-spinner="el-icon-loading"
            @click="getAllLists"
          >
            搜索
          </el-button>
        </el-input>
      </div>
    </div>
    <!--table板块-->
    <div ref="tableCon" class="tableCon">
      <el-table
        v-loading="searchLoading"
        :data="allDatas"
        :height="tableHeight || 'auto'"
        border
        fit
        style="width: 100%"
      >
        <el-table-column prop="contractName" label="合同名称" min-width="180" />
        <el-table-column prop="contractNo" label="合同编号" min-width="100" />
        <el-table-column
          prop="contractBeginDate"
          label="开始日期"
          min-width="120"
        >
          <template slot-scope="scope">
            {{
              scope.row.contractBeginDate
                ? scope.row.contractBeginDate.split(" ")[0]
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="contractEndDate"
          label="结束日期"
          min-width="120"
        >
          <template slot-scope="scope">
            {{
              scope.row.contractEndDate
                ? scope.row.contractEndDate.split(" ")[0]
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="contractAmount"
          label="合同金额"
          min-width="100"
        />
        <el-table-column
          prop="contractSigningDate"
          label="签约时间"
          min-width="100"
        >
          <template slot-scope="scope">
            {{
              scope.row.contractSigningDate
                ? scope.row.contractSigningDate.split(" ")[0]
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="contractSigningPersonName"
          label="签约人"
          min-width="100"
        />
        <el-table-column
          prop="contractRemark"
          label="备注"
          show-overflow-tooltip
          min-width="150"
        />
        <el-table-column label="操作" width="70px" align="center" fixed="right">
          <template slot-scope="scope">
            <div>
              <el-popover
                :ref="`popover-${scope.$index}`"
                placement="bottom-end"
                popper-class="tableOp"
                width="160"
                :popper-options="{
                  boundariesElement: 'opBox',
                  removeOnDestroy: true,
                }"
                trigger="click"
              >
                <div class="operation">
                  <ul>
                    <li @click="previewContract(scope.row)">预览</li>
                    <li @click="editContract(scope.row)">修改</li>
                  </ul>
                  <ul>
                    <li @click="downloadContract(scope.row)">下载合同</li>
                  </ul>
                  <ul>
                    <li @click="deleteContract(scope.row)">删除</li>
                  </ul>
                </div>
                <div slot="reference" class="opBox pointer">
                  <span class="el-icon-more c_3F61F1" />
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 S-->
    <div class="d_pag">
      <pagination
        :total="total || 0"
        :page.sync="search.pageIndex"
        :limit.sync="search.pageSize"
        @pagination="getAllLists"
      />
    </div>
    <!-- 分页 E-->
    <!-- 新建、修改合同   -->
    <el-dialog
      :title="ops === 'add' ? '新建合同' : '修改合同'"
      :visible.sync="isAddDialog"
      :close-on-click-modal="false"
      custom-class="comDialog"
      width="30%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <el-form
          ref="contractForm"
          :model="contractForm"
          :rules="rules"
          label-width="100px"
          class="dialogForm dialogInlineForm"
        >
          <el-form-item label="合同名称" prop="contractName">
            <el-input
              v-model="contractForm.contractName"
              placeholder="请输入合同名称"
              size="mini"
              clearable
            />
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNo">
            <el-input
              v-model="contractForm.contractNo"
              placeholder="请输入合同编号"
              size="mini"
              clearable
            />
          </el-form-item>
          <el-form-item label="合同金额(元)">
            <el-input
              v-model="contractForm.contractAmount"
              placeholder="请输入合同金额"
              size="mini"
              clearable
            />
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="contractForm.contractBeginDate"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="contractForm.contractEndDate"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item label="签约日期">
            <el-date-picker
              v-model="contractForm.contractSigningDate"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item label="签约人">
            <div class="flex flex_center">
              <div class="flex1">
                <el-input
                  v-model="contractForm.contractSigningPersonName"
                  placeholder="选择人员"
                  size="mini"
                  disabled
                />
              </div>
              <div class="ml10 btnPer">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-user"
                  @click="isperShow = true"
                  >选择人员</el-button
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="合同文件" prop="originalFileName">
            <el-upload
              class="avatar-uploader"
              action=" "
              :show-file-list="false"
              :http-request="myUpload"
              :before-upload="beforeUpload"
            >
              <div class="flex c_3F61F1">
                <i class="iconfont uploadIco mr5" /><span>上传文件</span>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label=" ">
            <div v-if="contractForm.file.fileSize" class="thumbnailBox flexs">
              <div class="icoBox">
                <template v-if="contractForm.file.fileType === '.pdf'">
                  <div class="fileIco f22">
                    <i class="iconfont pdfIco f22" />
                  </div>
                </template>
                <template
                  v-else-if="
                    contractForm.file.fileType === '.xls' ||
                    contractForm.file.fileType === '.xlsx' ||
                    contractForm.file.fileType === '.csv'
                  "
                >
                  <div class="fileIco f22" style="background: #54a55b">
                    <i class="iconfont ecelIco f22" />
                  </div>
                </template>
                <template
                  v-else-if="
                    contractForm.file.fileType === '.doc' ||
                    contractForm.file.fileType === '.docx'
                  "
                >
                  <div class="fileIco f22" style="background: #409eff">
                    <i class="iconfont wordIco f22" />
                  </div>
                </template>
                <template
                  v-else-if="
                    contractForm.file.fileType === '.ppt' ||
                    contractForm.file.fileType === '.pptx'
                  "
                >
                  <div class="fileIco f22">
                    <i class="iconfont pptIco f22" />
                  </div>
                </template>
                <template
                  v-else-if="
                    contractForm.file.fileType === '.zip' ||
                    contractForm.file.fileType === '.rar'
                  "
                >
                  <div class="fileIco f22">
                    <i class="iconfont zipIco f22" />
                  </div>
                </template>
                <template
                  v-else-if="
                    contractForm.file.fileType === '.jpg' ||
                    contractForm.file.fileType === '.jpeg' ||
                    contractForm.file.fileType === '.png' ||
                    contractForm.file.fileType === '.bmp' ||
                    contractForm.file.fileType === '.ico'
                  "
                >
                  <div class="fileIco f22">
                    <i class="iconfont imgIco f22" />
                  </div>
                </template>
                <template v-else>
                  <div class="fileIco f22">
                    <i class="iconfont otherFileIco f22" />
                  </div>
                </template>
              </div>
              <div class="uploadTxt">
                <div class="f12 fw">
                  {{ contractForm.file.originalFileName }}
                </div>
                <div class="C_999aaa">
                  {{ convertBytes(contractForm.file.fileSize) }}
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="备注" class="mt12">
            <el-input
              v-model="contractForm.contractRemark"
              type="textarea"
              placeholder="请输入内容"
              size="mini"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddDialog = false">取 消</el-button>
        <el-button
          v-if="ops === 'add'"
          v-loading="addLableLoading"
          :disabled="addLableLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="addSave"
          >保存</el-button
        >
        <el-button
          v-if="ops === 'modify'"
          v-loading="addLableLoading"
          :disabled="addLableLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="editSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 人员寻找弹框   -->
    <per-redio-dialog
      :per-visible.sync="isperShow"
      @getEmployee="getEmployee"
    />
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import perRedioDialog from "@/components/perDialogRedio";
import { formatbytes } from "@/utils";
export default {
  name: "",
  components: { Pagination, perRedioDialog },
  data() {
    return {
      ops: "add",
      isAddDialog: false, // 新建合同弹框是否打开
      isperShow: false, // 人员选择弹框是否打开
      addLableLoading: false,
      searchLoading: false, // 合同列表加载效果
      tableHeight: null,
      // 合同管理搜索条件
      search: {
        pageIndex: 1,
        pageSize: 30,
        certificationType: 0,
        customerCode: "",
        likeWords: "",
      },
      total: 0,
      allDatas: [], // 合同管理列表
      contractForm: {
        customerCode: "",
        contractNo: "",
        contractName: "",
        contractAmount: "",
        contractBeginDate: "",
        contractEndDate: "",
        contractSigningDate: "",
        contractSigningPerson: "",
        contractSigningPersonName: "",
        contractRemark: "",
        originalFileName: "",
        file: {
          fileType: "",
          fileSize: "",
          originalFileName: "",
          fileUrl: "",
          fileName: "",
          appendixPreview: "",
        },
      },
      lastFielUrl: "",
      rules: {
        originalFileName: [
          { required: true, message: "请上传资质", trigger: "change" },
        ],
        contractName: [
          {
            required: true,
            message: "请输入合同名称",
            trigger: ["change", "blur"],
          },
        ],
        contractNo: [
          {
            required: true,
            message: "请输入合同编号",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  created() {
    // 合同列表
    this.getAllLists();
  },
  mounted() {
    // 客户订单表格最高高度
    this.calHeight();
  },
  methods: {
    // 编辑合同保存
    editSave() {
      this.contractForm.customerCode = this.$route.query.customerCode;
      // 判断文件是否改变
      if (this.lastFielUrl !== this.contractForm.file.fileUrl) {
        this.contractForm.fileIsChange = true;
      } else {
        this.contractForm.fileIsChange = false;
      }
      const parmas = this.contractForm;
      this.$refs.contractForm.validate((valid) => {
        if (valid) {
          this.addLableLoading = true;
          this.$api.business
            .UpdateCustomerContract(parmas)
            .then((res) => {
              this.addLableLoading = false;
              this.isAddDialog = false;
              this.getAllLists();
              this.$message({
                message: "修改成功",
                type: "success",
              });
            })
            .catch(() => {
              this.addLableLoading = false;
            });
        }
      });
    },
    // 新建合同保存
    addSave() {
      this.contractForm.customerCode = this.$route.query.customerCode;
      const parmas = this.contractForm;
      this.$refs.contractForm.validate((valid) => {
        if (valid) {
          this.addLableLoading = true;
          this.$api.business
            .UploadCustomerContract(parmas)
            .then((res) => {
              this.addLableLoading = false;
              this.isAddDialog = false;
              this.getAllLists();
              this.$message({
                message: "新建成功",
                type: "success",
              });
            })
            .catch(() => {
              this.addLableLoading = false;
            });
        }
      });
    },
    // 修改详情
    editContract(data) {
      const parmas = {
        contractID: data.contractID,
      };
      this.ops = "modify";
      this.$api.business.GetCustomerContractDetail(parmas).then((res) => {
        this.contractForm = res;
        this.lastFielUrl = res.file.fileUrl;
        this.contractForm.originalFileName = res.file.originalFileName;
        this.contractForm.contractSigningPersonName = res.signingPersonName;
        this.isAddDialog = true;
      });
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

      // const whiteList = ["jpg", "png"];

      // if (whiteList.indexOf(fileSuffix) === 1) {
      //   this.$message.warning("不能上传图片");
      //   return false;
      // }
    },

    // 删除合同
    deleteContract(data) {
      const parmas = {
        contractID: data.contractID,
        contractCode: data.contractCode,
      };
      this.$confirm("确定删除当前客户合同, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.business.DeleteCustomerContract(parmas).then(() => {
          this.getAllLists();
          this.$message({
            message: "删除成功",
            type: "success",
          });
        });
      });
    },
    // 预览合同
    previewContract(data) {
      const parmas = {
        contractID: data.contractID,
        contractCode: data.contractCode,
      };
      this.$api.business.PreviewContractFile(parmas).then((res) => {
        window.open(res);
      });
    },
    // 下载合同
    downloadContract(data) {
      const parmas = {
        contractID: data.contractID,
        contractCode: data.contractCode,
      };
      this.$api.business.DownLoadContractFile(parmas).then((res) => {
        let first = res.lastIndexOf("."); //取到文件名开始到最后一个点的长度
        let namelength = res.length; //取到文件名长度
        let filesuffix = res.substring(first + 1, namelength); //截取获得后缀名
        const prefix = /^http(s)?:\/\/(.*?)\//;
        if (filesuffix == "txt") {
          fetch(res.replace(prefix, ""))
            .then((ress) => ress.blob())
            .then((blob) => {
              // 将链接地址字符内容转变成blob地址
              const element = document.createElement("a");
              element.href = URL.createObjectURL(blob);
              element.download = "合同文件"; // 下载文件的名字
              document.body.appendChild(element);
              element.click();
               document.body.removeChild(element)
            });
        } else if (
          filesuffix == "png" ||
          filesuffix == "jpg" ||
          filesuffix == "svg" ||
          filesuffix == "JPEG" ||
          filesuffix == "webp"
        ) {
          this.downloadByBlob(res.replace(prefix, ""), "合同文件");
        } else {
          window.open(res.replace(prefix, ""));
          // let link = document.createElement("a");
          // link.style.display = "none";
          // link.href = res;
          // link.setAttribute("download", "合同文件");
          // document.body.appendChild(link);
          // console.log(link);
          // link.click();
        }
      });
    },
    // 新建合同点击事件
    addClick() {
      this.isAddDialog = true;
      this.ops = "add";
    },

    download(href, name) {
      let eleLink = document.createElement("a");
      eleLink.download = name;
      eleLink.href = href;
      eleLink.click();
      eleLink.remove();
    },

    downloadByBlob(url, name) {
      let image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.src = url;
      image.onload = () => {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        canvas.toBlob((blob) => {
          let url = URL.createObjectURL(blob);
          this.download(url, name);
          // 用完释放URL对象
          URL.revokeObjectURL(url);
        });
      };
    },
    // 得到签约人
    getEmployee(val) {
      this.contractForm.contractSigningPerson = val.employeeCode;
      this.contractForm.contractSigningPersonName = val.employeeName;
    },
    // 上传合同
    myUpload(e) {
      const file = e.file;
      // const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      // const isLt2M = file.size / 1024 / 1024 < 2
      var formData = new FormData();
      formData.append("file", file);
      this.$api.common.UploadSingleFile(formData).then((res) => {
        this.contractForm.file.fileSize = res.fileSize;
        this.contractForm.file.originalFileName = res.originalName;
        this.contractForm.originalFileName = res.originalName;
        this.$forceUpdate();
        this.contractForm.file.fileType = res.fileExtension;
        this.contractForm.file.fileUrl = res.fileUrl;
        this.contractForm.file.fileName = res.fileName;
        this.contractForm.file.filePreview = res.appendixPreview || "";
        this.$refs['contractForm'].clearValidate(['originalFileName'])
      });
    },
    // 文件大小单位换算
    convertBytes(val) {
      return formatbytes(val);
    },
    // 合同列表
    getAllLists() {
      this.search.customerCode = this.$route.query.customerCode;
      const parmas = this.search;
      this.searchLoading = true;
      this.$api.business
        .PageCustomersContracts(parmas)
        .then((res) => {
          this.allDatas = res.list;
          this.total = res.totalCount;
          this.searchLoading = false;
        })
        .catch(() => {
          this.searchLoading = false;
        });
    },
    // 客户订单表格最高高度
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.tableCon.getBoundingClientRect();
        this.tableHeight = rect.height;
      });
    },
    // 弹框关闭事件
    closeDialog() {
      if (this.$refs.contractForm) {
        this.$refs.contractForm.resetFields();
      }
      this.contractForm = this.$options.data().contractForm;
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  height: 100%;
}
.thumbnailBox {
  background: #3f61f110;
  padding: 8px;

  .fileIco {
    color: #fff;
    width: 36px;
    height: 36px;
    line-height: 36px;
    text-align: center;
    border-radius: 4px;
    background: #e13335;
  }

  .icoBox {
    height: 36px;
    width: 36px;
  }

  .uploadTxt {
    line-height: 18px;
    margin-left: 10px;
  }
}
</style>
